package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"store/model/mysql"
	"store/pkg"

	"store/storerpc/internal/svc"
	"store/storerpc/storerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *storerpc.RegisterRequest) (*storerpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account =?", in.Account).Find(&user)

	register := mysql.User{
		Model:    gorm.Model{},
		Account:  in.Account,
		Password: pkg.MD5(in.Password),
	}
	if register.Account == user.Account {
		return nil, fmt.Errorf("账号已经注册,请重新输入")
	}
	mysql.DB.Debug().Model(&register).Create(&register)
	return &storerpc.RegisterResponse{Id: int64(register.ID)}, nil
}
